package com.doubi.controller;

import com.doubi.SystemHardwareInfo;
import com.doubi.common.config.shiro.ShiroUtil;
import com.doubi.constants.SystemConstants;
import com.doubi.controller.common.BaseController;
import com.doubi.model.sys.TSysPermission;
import com.doubi.model.sys.TSysUser;
import com.doubi.service.SysPermissionService;
import com.doubi.service.SysUserService;
import com.doubi.utils.DataUtil;
import com.doubi.utils.RandomValidateCodeUtil;
import com.doubi.vo.AppModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.doubi.constants.SystemConstants.SEESION_VERIFICATION_CODE;

@Slf4j
@Controller
public class IndexController extends BaseController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysPermissionService sysPermissionService;

    /**
     * 功能描述：后台主页
     *
     * @param model Model
     * @return 返回主页页面路径
     * @author MrDoubi 2019-06-26 10:57
     */
    @RequestMapping(value = {"/", "index"}, method = RequestMethod.GET)
    public String index(Model model) {
        return "index";
    }

    /**
     * 功能描述：登录页面
     *
     * @return 返回登陆页面路径
     * @author MrDoubi 2019-06-25 16:03
     */
    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String login() {
        return "login";
    }

    /**
     * Author:MrDoubi
     * Description: 目前是主页
     * Date:2019年1月5日 17:16:43
     *
     * @return 主页
     */
    @RequestMapping(value = "home", method = RequestMethod.GET)
    public String console() {
        return "web/home/console";
    }


    /**
     * 功能描述：登陆方法
     *
     * @param sysUser    TSysUser当前登录的TSysUser对象
     * @param vercode    验证码
     * @param rememberMe 是否记住密码
     * @param session    session
     * @return 返回AppModel对象
     * @author MrDoubi 2019-06-26 10:43
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    @ResponseBody
    public AppModel doLogin(TSysUser sysUser, String vercode, Long distance, boolean rememberMe, HttpSession session) {
        AppModel model = null;
        try {
            /*String index = (String) session.getAttribute("slider-X-index");
            if (!(distance >= (Long.parseLong(index) - 5) && distance <= (Long.parseLong(index) + 5))) {
                return new AppModel(-2, "图片验证失败！");
            }*/
            String sessionVercode = (String) session.getAttribute(SEESION_VERIFICATION_CODE);
            if (DataUtil.isEmpty(vercode)) {
                return new AppModel(-1, "请输入验证码！");
            }
            if (DataUtil.isEmpty(sessionVercode)) {
                return new AppModel(-1, "验证码已失效！");
            }
            if (!vercode.equalsIgnoreCase(sessionVercode)) {
                return new AppModel(-1, "验证码错误！");
            }
            Subject subject = SecurityUtils.getSubject();
            //创建用户名和密码的令牌
            AuthenticationToken token = new UsernamePasswordToken(sysUser.getAccount(), sysUser.getPassword(), rememberMe);
            //调用安全管理器
            subject.login(token);
            //重置登陆失败次数
            //sysUserService.updateResetSysUserFailNum(sysUser.getAccount());
            //登陆成功传递参数
            Map<String, Object> map = new HashMap<>();
            sysUser = ShiroUtil.getUser();
            session.setAttribute(SystemConstants.SESSION_KEY_USERINFO, sysUser);
//            List<TSysPermission> list = sysPermissionService.getMyRole(sysUser);
            List<TSysPermission> list = sysPermissionService.list();
            sysUser.setMyPermission(list);
            session.setAttribute(SystemConstants.SEESION_KEY_LEFTURLS, getMyUrl(list));
            ShiroUtil.setUser(sysUser);
            map.put("link", "index");
            model = new AppModel(0, "登录成功！", map);
        } catch (UnknownAccountException e) {
            model = new AppModel(-1, "用户不存在！", "");
        } catch (IncorrectCredentialsException e) {
//            sysUserService.updateSysUserFailNum(sysUser.getAccount());
            model = new AppModel(-1, "用户名/密码错误！", "");
        } catch (LockedAccountException e) {
            model = new AppModel(-1, "账号已被禁用或锁定！", "");
        } catch (AuthenticationException e) {
            model = new AppModel(-1, "登录失败：" + e.getMessage(), "");
        } catch (Exception e) {
            e.printStackTrace();

            model = new AppModel(-1, e.getMessage(), "");
        }
        return model;
    }

    @RequestMapping(value = "getMyMenu", method = RequestMethod.GET)
    @ResponseBody
    public Object getMyMenu(HttpSession session) {
        return session.getAttribute(SystemConstants.SEESION_KEY_LEFTURLS);
    }

    private List<TSysPermission> getMyUrl(List<TSysPermission> sysPermissions) {
        List<TSysPermission> list = new ArrayList<>();
        if (DataUtil.isNotEmpty(sysPermissions)) {
            for (TSysPermission sysPermission : sysPermissions) {
                if (sysPermission.getType() == 1) {
                    list.add(sysPermission);
                }
            }
        }
        return list;
    }


    /**
     * 功能描述：退出登陆
     *
     * @author MrDoubi 2019-06-26 10:26
     */
    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            subject.logout();
        }
        return "redirect:login";
    }


    /**
     * MrDoubi
     * 2019年10月27日 17:15:20
     * 系统硬件信息页面
     *
     * @author administrator
     */
    @RequestMapping("/systemInfo")
    public String systemInfo(Model model) {
        SystemHardwareInfo systemHardwareInfo = new SystemHardwareInfo();
        systemHardwareInfo.copyTo();
        model.addAttribute("server", systemHardwareInfo);
        return "web/systemInfo/systemInfo";
    }


    /**
     * 生成验证码
     */
    @GetMapping(value = "/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
            response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            randomValidateCode.getRandcode(request, response);//输出验证码图片方法
        } catch (Exception e) {
            log.error("获取验证码失败>>>> ", e);
        }
    }
}
